const CosmeticsDetailModule = require('../../modules/base/cosmeticsDetail');
const FocusDetailModule = require('../../modules/recommend/focusDetail');
const LikeClassify = require('../../modules/recommend/likeClassify')
// const ClassifyModule = require('../../modules/base/cosmeticsClassify')
const Map = require('../../modules/map/classifyFieldMap')
const path = require('path')
const util = require('../../utils/util')
const imagemin = require('../../utils/imagemin')
const recommend = require('../../utils/recommend')
const qs = require('querystring');
const sequelize = require('sequelize');
const Op = sequelize.Op;

class CosmeticsDetailControllers {
  /**
   * spider新增化妆品商品详情
   */
  static async addCosmeticsDetail(key, list) {
    for (let i=0; i <= list.length - 1; i++) {
      await CosmeticsDetailModule.addCosmeticsDetail({
        title: list[i].title,
        link: list[i].link,
        picture: list[i].picture,
        price: list[i].price,
        kw: key
      })
    }
  }

  /**
   * spider获取化妆品信息
   */
  static async getCosmeticsDetail(where) {
    return await CosmeticsDetailModule.getCosmeticsDetail(where)
  }

  /**
   * spider更新classify
   */
  static async updateClassify(where, classify, con) {
    return await CosmeticsDetailModule.updateClassify(where, classify, con)
  }

  /**
   * 获取信息列表
   */
  static async getCosmeticsDetailList(ctx) {
    const req = qs.parse(ctx.request.url.split('?')[1])
    let where = {}
    if (req.title) {
      where.title = {
        [Op.like]: `%${req.title}%`
      }
    }
    if (req.classify) {
      where.classify = {
        [Op.like]: `%${req.classify}%`
      }
    }
    if (req.price) {
      where.price = {
        [Op.like]: `%${req.price}.00%`
      }
    }

    const total = (await CosmeticsDetailModule.getCosmeticsDetail(where)).length
    try {
      const list = await CosmeticsDetailModule.getCosmeticsDetail(where, req.total, req.pagination)

      ctx.body = {
        code: 200,
        data: {
          list,
          total,
          pagination: +req.pagination
        }
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }
  
  /**
   * 推荐列表
   */
  static async getRecommendList(ctx) {
    const req = qs.parse(ctx.request.url.split('?')[1])
    if (!req.userId) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    try {
      const focusList = await FocusDetailModule.getFocus({
        userId: req.userId
      })

      let details

      if (focusList.length) {
        details = await recommend.detail(req.userId)
      } else {
        details = await recommend.user(req.userId)
      }

      const likeExist = await LikeClassify.getLikeClassify({
        userId: req.userId
      })
      let likeRecommend = []
      let likeR = 0
      if (likeExist) {
        likeR = 4
        const like = JSON.parse(likeExist.classifyKey)
        console.log(like)
        const mapSql = like.map(item => { return {key: item} })
        const classify = (await Map.getMap({
          [Op.or]: mapSql
        })).map(item => { return {classify: {[Op.like]: `%${item.value}%`}} })
        likeRecommend = await CosmeticsDetailModule.getDetail({
          [Op.or]: classify
        }, 4, true)
      }

      let list = []
      details.forEach(d => {
        list.push({detail_id: d})
      })

      const sysRecommend = await CosmeticsDetailModule.getDetail({
        [Op.or]: list.slice(0, (8 - (likeRecommend ? likeRecommend.length : 0)))
      })

      const data = likeRecommend.concat(sysRecommend)
      ctx.body = {
        code: 200,
        data
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }

  /**
   * 用户获取单个信息
   */
  static async getCosmeticsDetailItem(ctx) {
    const req = qs.parse(ctx.request.url.split('?')[1])
    if (!req.detail_id) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    try {
      let item = await CosmeticsDetailModule.getCosmeticsDetailItem({detail_id: req.detail_id})
      if (req.user_id) {
        let focus = await FocusDetailModule.getFocus({
          detailId: req.detail_id,
          userId: req.user_id
        })
        item.focus = Boolean(focus.length)
      }
      item.classify = JSON.parse(item.classify)
      ctx.body = {
        code: 200,
        data: item
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }

  /**
   * 上传缩略图
   */
  static async uploadPicture(ctx) {
    const req = ctx.request
    const image = path.basename(req.files.image.path)

    const ext = image.split('.')
    if (!['jpg', 'png'].includes(ext[ext.length - 1])) {
      ctx.body = {
        code: 416,
        msg: '不支持此格式'
      }
      return
    }

    const targetDir = './public/images/detailPicture'
    util.isDirExists(targetDir)

    await imagemin.imageminComp(`./public/uploads/${image}`, `./public/images/detailPicture/`)
    const currentImage = image.split('.')[0] + '.webp'
    const url = `${ctx.origin}/images/detailPicture/${currentImage}`

    ctx.body = {
      code: 200,
      data: {
        url
      }
    }
  }

  /**
   * 编辑化妆品
   */
  static async editDetailByAdmin(ctx) {
    const req = ctx.request.body
    if (!req.title || !req.link || !req.picture || !req.price || !req.detailId) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    try {
      await CosmeticsDetailModule.update({
        detail_id: req.detailId
      }, {
        title: req.title,
        link: req.link,
        picture: req.picture,
        price: '￥' + req.price
      })

      ctx.body = {
        code: 200,
        msg: 'success'
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }

  /**
   * 新增化妆品
   */
  static async addDetailByAdmin(ctx) {
    const req = ctx.request.body
    if (!req.title || !req.link || !req.picture || !req.classify || !req.price) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    try {
      let classify = {
        classify: req.classify,
        type: 1
      }
      await CosmeticsDetailModule.addCosmeticsDetail({
        title: req.title,
        link: req.link,
        picture: req.picture,
        price: '￥' + req.price,
        classify: JSON.stringify(classify),
        kw: '自建'
      })

      ctx.body = {
        code: 200,
        msg: 'success'
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }
}

module.exports = CosmeticsDetailControllers
